package com.zhuliwei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.MenuAddDto;
import com.zhuliwei.domain.dto.MenuDto;
import com.zhuliwei.domain.entity.Menu;
import com.zhuliwei.service.MenuService;
import com.zhuliwei.utils.BeanCopyUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 菜单管理控制层
 *
 * @author 朱力维
 * @time 2022/10/28 10:57
 **/
@RestController
@RequestMapping("/system/menu")
@Api(tags = "菜单", description = "菜单管理相关接口")
public class MenuController {
    @Resource
    private MenuService menuService;

    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('system:menu:list')")
    public ResponseResult list(MenuDto menuDto) {
        return menuService.menuList(menuDto);
    }

    @PostMapping
    @PreAuthorize("@ps.hasPermission('system:menu:add')")
    public ResponseResult add(@RequestBody MenuAddDto menuAddDto) {
        Menu menu = BeanCopyUtils.copyBean(menuAddDto, Menu.class);
        menuService.save(menu);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult detailMenu(@PathVariable String id) {
        Menu menu = menuService.getById(id);
        return ResponseResult.okResult(menu);
    }

    @PutMapping
    @PreAuthorize("@ps.hasPermission('system:menu:update')")
    public ResponseResult update(@RequestBody Menu menu) {
        menuService.updateById(menu);
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{menuId}")
    @PreAuthorize("@ps.hasPermission('system:menu:delete')")
    public ResponseResult delete(@PathVariable String menuId) {
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Menu::getParentId, menuId);
        Long count = menuService.count(lqw);
        if (count > 0) {
            return ResponseResult.errorResult(500, "存在子菜单不允许删除");
        }
        menuService.removeById(menuId);
        return ResponseResult.okResult();
    }

    /**
     * 获取菜单树
     */
    @GetMapping("/treeselect")
    public ResponseResult treeselect(){
        return menuService.treeselect();
    }

    /**
     * 获取角色所关联的菜单树
     */
    @GetMapping("/roleMenuTreeselect/{id}")
    public ResponseResult treeselectById(@PathVariable String id){
        return menuService.treeselectById(id);
    }
}
